const Router = require('koa-router')
const jwt = require('jsonwebtoken')
const { PRIVATE_KEY } = require('@/app/config')
const { resDesign, menusTree } = require('@/utils/dataDesign')
const UserService = require('@/service/login.service')
const { verifyLogin } = require('@/middleware/auth.mid')
const { verifyUser } = require('@/middleware/user.mid')

const userRouter = new Router({ prefix: '/user' })

/** 注册用户 */
userRouter.post('/register', verifyUser, async (ctx) => {
  try {
    // 获取用户传递的参数
    const user = ctx.request.body
    // 查询数据
    await UserService.create(user)
    // 返回数据
    ctx.body = resDesign({ msg: '注册成功!' })
  } catch (error) {
    console.log(error)
  }
})

/** 登录 */
userRouter.post('/login', verifyLogin, async (ctx) => {
  try {
    const { id, account } = ctx.user
    const token = jwt.sign({ id, account }, PRIVATE_KEY, {
      expiresIn: '12h',
      algorithm: 'RS256',
    })
    ctx.body = resDesign({ data: { id, account, token }, msg: '登录成功!' })
  } catch (error) {
    console.log(error)
  }
})

/** 获取用户信息 */
userRouter.get('/userinfo', async (ctx) => {
  try {
    const { id } = ctx.query
    const result = await UserService.getUserInfo(id)
    ctx.body = resDesign({ data: result })
  } catch (error) {
    console.log(error)
  }
})

/** 获取用户菜单 */
userRouter.get('/routers', async (ctx) => {
  try {
    const { id } = ctx.query
    const result = await UserService.queryMenuList(id)
    const treeMenus = menusTree(result, 0)
    ctx.body = resDesign({ data: treeMenus })
  } catch (error) {
    console.log(error)
  }
})

/** 测试token */
userRouter.get('/test/token', async (ctx) => {
  ctx.body = resDesign({ msg: '验证成功!' })
})

module.exports = userRouter
